import { defineStore } from 'pinia'
import { isObject } from '@vue/shared'
import { useDark, useToggle } from '@vueuse/core'
import { cacheEnum } from '~/enums/cache'
import themeUtil from '~/utils/theme'
import defaultSetting from '~/config/setting'

export const useConfStore = defineStore('confStore', {
    state: () => {
        const cacheSetting = useCookie(cacheEnum.SETTING_KEY)
        const state: any = {
            isDarkColor: false,
            ...defaultSetting
        }

        const settingJson = cacheSetting.value || {}
        if (isObject(settingJson)) {
            Object.assign(state, settingJson)
        }

        return state
    },
    actions: {
        /**
         * 修改配置
         */
        setSetting(data: Record<string, any>): void {
            const oneWeek = 7 * 24 * 60 * 60 * 1000
            const storageSetting = useCookie(cacheEnum.SETTING_KEY, {
                expires: new Date(Date.now() + oneWeek)
            })

            const { key, value } = data
            if (Reflect.has(this, key)) {
                this[key] = value
            }

            const settings: any = Object.assign({}, this.$state)
            delete settings.settingShow
            storageSetting.value = JSON.stringify(settings)
        },
        /**
         * 修改主题
         */
        setTheme(dark: boolean, color: string = ''): void {
            if (color) {
                this.primaryTheme = color
            } else {
                color = this.primaryTheme
            }

            themeUtil.setTheme({
                primary: color,
                success: this.successTheme,
                warning: this.warningTheme,
                danger: this.dangerTheme,
                error: this.errorTheme,
                info: this.infoTheme
            }, dark)

            const isDark = useDark({
                selector: 'html',
                valueDark: 'dark',
                valueLight: 'light',
            })

            isDark.value = !dark
            useToggle(isDark)()

            this.setSetting({
                key: 'isDarkColor',
                value: dark
            })
        }
    }
})

export default useConfStore
